package user

import (
	monproto "gollect/proto"
	"sort"
	"time"

	"github.com/shirou/gopsutil/v3/process"
)

type userInfo struct {
	User string
	CPU  float64
	Mem  float32
}

// Resource threshold constants
const (
	CPUThreshold    = 5.0 // 5% CPU usage threshold
	MemoryThreshold = 5.0 // 5% memory usage threshold
)

func CollectTopN(n int, interval time.Duration) []*monproto.UserInfo {
	procs, err := process.Processes()
	if err != nil {
		return nil
	}
	userMap := make(map[string]*userInfo)
	for _, p := range procs {
		u, _ := p.Username()
		cpu, _ := p.CPUPercent()
		mem, _ := p.MemoryPercent()
		if u == "" {
			continue
		}
		if _, ok := userMap[u]; !ok {
			userMap[u] = &userInfo{User: u}
		}
		userMap[u].CPU += cpu
		userMap[u].Mem += mem
	}
	infos := make([]*userInfo, 0, len(userMap))
	for _, info := range userMap {
		infos = append(infos, info)
	}
	sort.Slice(infos, func(i, j int) bool {
		return infos[i].CPU > infos[j].CPU
	})
	var result []*monproto.UserInfo
	for i := 0; i < len(infos); i++ {
		info := infos[i]
		// Apply threshold filter: skip if both CPU and memory are below threshold
		if info.CPU < CPUThreshold && info.Mem < MemoryThreshold {
			continue
		}
		// Stop after collecting n users that meet the threshold
		if len(result) >= n {
			break
		}
		result = append(result, &monproto.UserInfo{
			User: info.User,
			Cpu:  float32(info.CPU / 100.0),
			Mem:  float32(info.Mem / 100.0),
		})
	}
	return result
}
